/**
 * 路由鉴权
 */
import {
	getCookieValue
} from '~/util/index.js';
import aes from '~/util/aes.js'

export default function({
	route,
	req,
	res,
	redirect,
	app
}) {
	let isServer = process.server;
	let isClient = process.client;
	let redirectURL = '/';//默认跳转到后台管理的登录页
	let token, path, path2; //path是路由地址，path2是路由地址加query的全路径
	//在服务器端
	if (isServer) {
		let cookies = req.headers.cookie;
		token = getCookieValue('token', cookies);
		path = req.url.split('?')[0];
		path2 = req.originalUrl; //req.originalUrl是全路径，带query
	}
	//在客户端
	if (isClient) {
		token = app.$cookies.get('token');
		path = route.path;
		path2 = route.fullPath;
	}
	/**
	 * TODO：①一级鉴权：判断是否已登录
	 * TIPS：采用白名单策略（不在数组中即需要验证是否登录，没登录跳转到登录页）
	 * 判断路由得判断不带query的那一部分路径(例如/index，即上述的path)，跳转到登录页时得告诉登录页跳转过来的路由全路径(例如/index?a=1，即上述的path2)
	 * ADDITIONAL:登录，注册的路由是判断是否登录时最起码要过滤的路由页面。
	 */
	let routeArr = ["/","/user/apply","/login","/register","/user/agreement", '/admin', '/admin/login'];
	// 1.前台管理和后台管理的登录判断（前台管理和后台管理）
	if (routeArr.indexOf(path) == -1) {
		if (!token) {
			//跳到登录页
			// redirect(redirectURL + '?from=' + path2)
			if(path.slice(0, 6) === '/admin') {
				// 如果为后台则跳转后台登入界面
				redirect(`/admin?from=${path2}`)
			}else{
				// 否则跳转到前台界面
				redirect(redirectURL + '?from=' + path2)
			}
		}
	}
}

function isNull(value){
	if(value === null || value === '' || value === undefined){
		return true;
	}else{
		return false
	}
}